package com.lifeverse.controller;

import com.lifeverse.common.ApiResponse;
import com.lifeverse.dto.LifeEntityCreateDTO;
import com.lifeverse.dto.LifeEntityDTO;
import com.lifeverse.dto.LifeEntityUpdateDTO;
import com.lifeverse.entity.LifeEntity;
import com.lifeverse.entity.enums.LifeEntityStatus;
import com.lifeverse.entity.enums.LifeEntityType;
import com.lifeverse.mapper.LifeEntityMapper;
import com.lifeverse.service.LifeEntityService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 生命体管理控制器
 * 提供生命体的REST API接口
 */
@Slf4j
@RestController
@RequestMapping("/api/life-entities")
@RequiredArgsConstructor
@Validated
@Tag(name = "生命体管理", description = "生命体的创建、查询、更新和删除操作")
public class LifeEntityController {

    private final LifeEntityService lifeEntityService;
    private final LifeEntityMapper lifeEntityMapper;

    /**
     * 分页查询生命体列表
     */
    @GetMapping
    @Operation(summary = "分页查询生命体列表", description = "支持按名称、类型、状态进行筛选和分页查询")
    public ResponseEntity<ApiResponse<Page<LifeEntityDTO>>> getLifeEntities(
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String search,
            @Parameter(description = "生命体类型") @RequestParam(required = false) LifeEntityType type,
            @Parameter(description = "生命体状态") @RequestParam(required = false) LifeEntityStatus status,
            @Parameter(description = "页码，从0开始") @RequestParam(defaultValue = "0") @Min(0) int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") @Min(1) int size,
            @Parameter(description = "排序字段") @RequestParam(defaultValue = "createdAt") String sort,
            @Parameter(description = "排序方向") @RequestParam(defaultValue = "desc") String direction) {
        
        log.debug("Querying life entities - search: {}, type: {}, status: {}, page: {}, size: {}", 
                 search, type, status, page, size);
        
        // 创建排序对象
        Sort.Direction sortDirection = "asc".equalsIgnoreCase(direction) ? 
            Sort.Direction.ASC : Sort.Direction.DESC;
        Sort sortObj = Sort.by(sortDirection, sort);
        
        // 创建分页对象
        Pageable pageable = PageRequest.of(page, size, sortObj);
        
        // 查询数据
        Page<LifeEntity> entityPage = lifeEntityService.findAll(search, type, status, pageable);
        
        // 转换为DTO
        Page<LifeEntityDTO> dtoPage = entityPage.map(lifeEntityMapper::toDTO);
        
        return ResponseEntity.ok(ApiResponse.success(dtoPage));
    }

    /**
     * 根据ID查询生命体详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "查询生命体详情", description = "根据ID获取生命体的详细信息")
    public ResponseEntity<ApiResponse<LifeEntityDTO>> getLifeEntityById(
            @Parameter(description = "生命体ID") @PathVariable @NotNull Long id) {
        
        log.debug("Getting life entity by id: {}", id);
        
        return lifeEntityService.findById(id)
            .map(entity -> ResponseEntity.ok(ApiResponse.success(lifeEntityMapper.toDTO(entity))))
            .orElse(ResponseEntity.status(HttpStatus.NOT_FOUND)
                .body(ApiResponse.error("生命体不存在")));
    }

    /**
     * 创建新的生命体
     */
    @PostMapping
    @Operation(summary = "创建生命体", description = "创建一个新的数字生命体")
    public ResponseEntity<ApiResponse<LifeEntityDTO>> createLifeEntity(
            @Parameter(description = "生命体信息") @Valid @RequestBody LifeEntityCreateDTO createDTO) {
        
        log.info("Creating new life entity: {}", createDTO.getName());
        
        try {
            LifeEntity entity = lifeEntityMapper.toEntity(createDTO);
            LifeEntity createdEntity = lifeEntityService.create(entity);
            LifeEntityDTO dto = lifeEntityMapper.toDTO(createdEntity);
            return ResponseEntity.status(HttpStatus.CREATED)
                .body(ApiResponse.success(dto, "生命体创建成功"));
        } catch (IllegalArgumentException e) {
            log.warn("Failed to create life entity: {}", e.getMessage());
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 更新生命体信息
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新生命体", description = "更新指定生命体的信息")
    public ResponseEntity<ApiResponse<LifeEntityDTO>> updateLifeEntity(
            @Parameter(description = "生命体ID") @PathVariable @NotNull Long id,
            @Parameter(description = "更新的生命体信息") @Valid @RequestBody LifeEntityUpdateDTO updateDTO) {
        
        log.info("Updating life entity: {}", id);
        
        try {
            LifeEntity updateEntity = lifeEntityMapper.toEntity(updateDTO);
            LifeEntity updatedEntity = lifeEntityService.update(id, updateEntity);
            LifeEntityDTO dto = lifeEntityMapper.toDTO(updatedEntity);
            return ResponseEntity.ok(ApiResponse.success(dto, "生命体更新成功"));
        } catch (IllegalArgumentException e) {
            log.warn("Failed to update life entity {}: {}", id, e.getMessage());
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 删除生命体
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除生命体", description = "软删除指定的生命体")
    public ResponseEntity<ApiResponse<Void>> deleteLifeEntity(
            @Parameter(description = "生命体ID") @PathVariable @NotNull Long id) {
        
        log.info("Deleting life entity: {}", id);
        
        try {
            lifeEntityService.delete(id);
            return ResponseEntity.ok(ApiResponse.success(null, "生命体删除成功"));
        } catch (IllegalArgumentException e) {
            log.warn("Failed to delete life entity {}: {}", id, e.getMessage());
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 激活生命体
     */
    @PostMapping("/{id}/activate")
    @Operation(summary = "激活生命体", description = "将生命体状态设置为活跃")
    public ResponseEntity<ApiResponse<LifeEntity>> activateLifeEntity(
            @Parameter(description = "生命体ID") @PathVariable @NotNull Long id) {
        
        log.info("Activating life entity: {}", id);
        
        try {
            LifeEntity activatedEntity = lifeEntityService.activate(id);
            return ResponseEntity.ok(ApiResponse.success(activatedEntity, "生命体激活成功"));
        } catch (IllegalArgumentException e) {
            log.warn("Failed to activate life entity {}: {}", id, e.getMessage());
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 休眠生命体
     */
    @PostMapping("/{id}/dormant")
    @Operation(summary = "休眠生命体", description = "将生命体状态设置为休眠")
    public ResponseEntity<ApiResponse<LifeEntity>> dormantLifeEntity(
            @Parameter(description = "生命体ID") @PathVariable @NotNull Long id) {
        
        log.info("Setting life entity to dormant: {}", id);
        
        try {
            LifeEntity dormantEntity = lifeEntityService.dormant(id);
            return ResponseEntity.ok(ApiResponse.success(dormantEntity, "生命体休眠成功"));
        } catch (IllegalArgumentException e) {
            log.warn("Failed to set life entity {} to dormant: {}", id, e.getMessage());
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 进化生命体
     */
    @PostMapping("/{id}/evolve")
    @Operation(summary = "进化生命体", description = "触发生命体的进化过程")
    public ResponseEntity<ApiResponse<LifeEntity>> evolveLifeEntity(
            @Parameter(description = "生命体ID") @PathVariable @NotNull Long id) {
        
        log.info("Evolving life entity: {}", id);
        
        try {
            LifeEntity evolvedEntity = lifeEntityService.evolve(id);
            return ResponseEntity.ok(ApiResponse.success(evolvedEntity, "生命体进化成功"));
        } catch (IllegalArgumentException e) {
            log.warn("Failed to evolve life entity {}: {}", id, e.getMessage());
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 获取生命体统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取统计信息", description = "获取生命体的各种统计数据")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getStatistics() {
        
        log.debug("Getting life entity statistics");
        
        Map<String, Object> statistics = lifeEntityService.getStatistics();
        return ResponseEntity.ok(ApiResponse.success(statistics));
    }

    /**
     * 获取活跃的生命体列表
     */
    @GetMapping("/active")
    @Operation(summary = "获取活跃生命体", description = "获取当前活跃状态的生命体列表")
    public ResponseEntity<ApiResponse<List<LifeEntity>>> getActiveEntities() {
        
        log.debug("Getting active life entities");
        
        List<LifeEntity> activeEntities = lifeEntityService.findActiveEntities();
        return ResponseEntity.ok(ApiResponse.success(activeEntities));
    }

    /**
     * 获取需要关注的生命体
     */
    @GetMapping("/attention-needed")
    @Operation(summary = "获取需要关注的生命体", description = "获取健康度或能量较低的生命体列表")
    public ResponseEntity<ApiResponse<List<LifeEntity>>> getEntitiesNeedingAttention() {
        
        log.debug("Getting life entities needing attention");
        
        List<LifeEntity> entities = lifeEntityService.findEntitiesNeedingAttention();
        return ResponseEntity.ok(ApiResponse.success(entities));
    }

    /**
     * 获取最近活跃的生命体
     */
    @GetMapping("/recently-active")
    @Operation(summary = "获取最近活跃的生命体", description = "获取指定时间内活跃的生命体列表")
    public ResponseEntity<ApiResponse<List<LifeEntity>>> getRecentlyActiveEntities(
            @Parameter(description = "小时数") @RequestParam(defaultValue = "24") @Min(1) int hours) {
        
        log.debug("Getting recently active life entities (last {} hours)", hours);
        
        List<LifeEntity> entities = lifeEntityService.findRecentlyActive(hours);
        return ResponseEntity.ok(ApiResponse.success(entities));
    }

    /**
     * 批量更新生命体状态
     */
    @PutMapping("/batch/status")
    @Operation(summary = "批量更新状态", description = "批量更新多个生命体的状态")
    public ResponseEntity<ApiResponse<Void>> batchUpdateStatus(
            @Parameter(description = "生命体ID列表") @RequestParam List<Long> ids,
            @Parameter(description = "目标状态") @RequestParam LifeEntityStatus status) {
        
        log.info("Batch updating {} life entities to status: {}", ids.size(), status);
        
        try {
            lifeEntityService.batchUpdateStatus(ids, status);
            return ResponseEntity.ok(ApiResponse.success(null, "批量更新成功"));
        } catch (Exception e) {
            log.error("Failed to batch update life entities: {}", e.getMessage());
            return ResponseEntity.badRequest()
                .body(ApiResponse.error("批量更新失败: " + e.getMessage()));
        }
    }
}